package com.maiji.cloud.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.config.MyRedisConfig;
import com.maiji.cloud.entities.community.ComMsgCollect;
import com.maiji.cloud.entities.community.ComMsgInfo;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.mapper.ComMsgCollectMapper;
import com.maiji.cloud.mapper.ComMsgInfoMapper;
import com.maiji.cloud.microservice.UserInfoService;
import com.maiji.cloud.request.BaseInputDto;
import com.maiji.cloud.request.IdInputDto;
import com.maiji.cloud.response.BaseOutPutDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.service.ComCommentService;
import com.maiji.cloud.service.ComMsgCollectService;
import com.maiji.cloud.service.CommunityService;
import com.maiji.cloud.utils.RedisUtil;
import com.maiji.cloud.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;


import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class ComMsgCollectServiceImpl extends ServiceImpl<ComMsgCollectMapper, ComMsgCollect> implements ComMsgCollectService {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private CommunityService communityService;


    /**
     * 动态收藏
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto<String> collect(@RequestBody BaseInputDto<IdInputDto> inputDto , @RequestHeader("maijiToken")String maijiToken){
        BaseOutPutDto<String> outPutDto = new BaseOutPutDto();

        AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
        String userId = appUser.getUuId();

        ComMsgCollect msgCollect = new ComMsgCollect();
        msgCollect.setBelongId(inputDto.getData().getId());
        msgCollect.setCollecterId(userId);

        try{

            ComMsgInfo msgInfo = communityService.selectById(inputDto.getData().getId());
            msgCollect.setCollectTime(TimeUtil.getCurDateStamp());
            if(insert(msgCollect)){
                msgInfo.setCollect_count(msgInfo.getCollect_count()+1);
                outPutDto.setStatus(Status.SUCCESS);
                outPutDto.setMessage("收藏成功");
            }else{
                outPutDto.setStatus(Status.ERROR);
                outPutDto.setMessage("已经收藏过了");
            }

            if(msgInfo.getPriority() == 0 && msgInfo.getCollect_count() >= 5){
//                msgInfo.setPriority(1);
            }
            communityService.updateById(msgInfo);

            return outPutDto;
        }catch (Exception exception){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage("已经收藏过了");
            return outPutDto;
        }
    }

    /**
     * 取消动态收藏
     * @param inputDto
     * @param maijiToken
     * @return
     */
    @Override
    public BaseOutPutDto<String> cancelCollect(@RequestBody BaseInputDto<IdInputDto> inputDto ,@RequestHeader("maijiToken")String maijiToken){

        BaseOutPutDto<String> outPutDto = new BaseOutPutDto();

        AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
        String userId = appUser.getUuId();

        try{

            ComMsgInfo msgInfo = communityService.selectById(inputDto.getData().getId());
            ComMsgCollect msgCollect = new ComMsgCollect();
            msgCollect.setBelongId(inputDto.getData().getId());
            msgCollect.setCollecterId(userId);
            EntityWrapper<ComMsgCollect> discountCouponEntityWrapper = new EntityWrapper<>();
            discountCouponEntityWrapper.setEntity(msgCollect);
            if(delete(discountCouponEntityWrapper)){
                msgInfo.setCollect_count(msgInfo.getCollect_count()-1);
                outPutDto.setStatus(Status.SUCCESS);
                outPutDto.setData("取消成功");
            }else{
                outPutDto.setStatus(Status.ERROR);
                outPutDto.setData("取消失败");
            }
            communityService.updateById(msgInfo);
            return outPutDto;
        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setData("取消失败");
            return outPutDto;
        }
    }

    /**
     * 获取用户收藏的社区IDs
     * @param userId
     * @return
     */
    public List<String> getUserCollectIds(String userId,Integer pageNo,Integer size){

        try{
            EntityWrapper<ComMsgCollect> entityWrapper = new EntityWrapper<>();
            ComMsgCollect middleUserMessage = new ComMsgCollect();
            middleUserMessage.setCollecterId(userId);
            entityWrapper.setEntity(middleUserMessage);
            entityWrapper.orderBy("collect_time",false);
            Page<ComMsgCollect> page = new Page(pageNo,size);
            List<ComMsgCollect> msgCollects = selectPage(page,entityWrapper).getRecords();
            List<String> belongIds = msgCollects.parallelStream().map(ComMsgCollect::getBelongId).collect(Collectors.toList());
            return belongIds;

        }catch (Exception exc){
            return null;
        }

    }

    /**
     * 批量删除用户收藏动态（空参为清空收藏）
     * @param inputDto
     * @param maijiToken
     * @return
     */
    public BaseOutPutDto cancelCollectionMsgs(BaseInputDto<List<String>> inputDto,String maijiToken){
        BaseOutPutDto outPutDto = new BaseOutPutDto();
        try{
            AppUser appUser = RedisUtil.getAppUserByRedis(redisTemplate, MyRedisConfig.REDISDATABASENO, maijiToken, userInfoService);
            String userId = appUser.getUuId();
            EntityWrapper<ComMsgCollect> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("collecter_id", userId);
            List<String>msgIds = inputDto.getData();
            if (msgIds == null || msgIds.size() == 0)
                msgIds = selectList(entityWrapper).parallelStream().map(ComMsgCollect::getBelongId).collect(Collectors.toList());
            if (msgIds.size() == 0){
                outPutDto.setStatus(Status.SUCCESS);
                return outPutDto;
            }
            entityWrapper.in("belong_id", msgIds);
            if (delete(entityWrapper)){
                List<ComMsgInfo> msgInfos = communityService.selectBatchIds(msgIds).parallelStream().map(msgInfo ->
                    msgInfo.setCollect_count(msgInfo.getCollect_count()-1)
                ).collect(Collectors.toList());
                communityService.updateBatchById(msgInfos);
                outPutDto.setStatus(Status.SUCCESS);
            }

        }catch (Exception exc){
            outPutDto.setStatus(Status.ERROR);
            outPutDto.setMessage(exc.getMessage());

        }
        return outPutDto;
    }


}
